#include "QueryMicroMan.h"
#include <QStringList>
#include <QTextCodec>

//-------------------------------------

QueryMicroMan::QueryMicroMan(QObject *parent) :
    QObject(parent),
    maxtimeout( 500 ),
    sock( new QTcpSocket( this ) ),
    timer( new QTimer( this ) ),
    locker( 0 )
{
    codec = QTextCodec::codecForName( "ISO 8859-5" );

    connect( timer, SIGNAL( timeout() ), this, SLOT( onTimeout() ) );
    connect( sock, SIGNAL( connected() ), this, SLOT( onConnected() ) );
    connect( sock, SIGNAL( readyRead() ), this, SLOT( onReadyRead() ) );
    connect( sock, SIGNAL( disconnected() ), this, SIGNAL( sgnDisconnected() ) );
}

//-------------------------------------

void QueryMicroMan::Connect( QString h, quint16 p )
{
    if( !sock->isOpen() )
    {
        if( sock->open( QIODevice::ReadWrite ) )
        {
            if( sock->state() == QAbstractSocket::UnconnectedState )
            {
                sock->connectToHost( h, p );
            }
            else
            {
                sock->close();
            }
        }
    }
}

//-------------------------------------

void QueryMicroMan::Disconnect()
{
    if( sock->isOpen() )
    {
        sock->close();
    }
}

//-------------------------------------

void QueryMicroMan::onConnected()
{
    emit sgnConnected();
}

//-------------------------------------

void QueryMicroMan::ExecCmd( const QString cmd, bool WaitForEnd )
{
    waitForEnd = WaitForEnd;
    if( locker == 0 )
        LOCK();
    outStr.clear();
    QAbstractSocket::SocketState st = sock->state();
    if( st == QAbstractSocket::ConnectedState )
    {
        timer->start( maxtimeout );

        sock->write( cmd.toAscii() );
        sock->write( "\n" );
    }
}

//-------------------------------------

void QueryMicroMan::onReadyRead()
{
    //if( locker == 0 )
    //    LOCK();

    timer->stop();

    QTextStream stream( sock );
    stream.setCodec( codec );

    while( sock->bytesAvailable() )
    {
        outStr = outStr + stream.readAll();
    }

    if( !waitForEnd )
    {
        UNLOCK();
        emit sgnSendResponse( outStr );
    }
    else if( outStr.contains( "ERR" ) )
    {
        UNLOCK();
        emit sgnError();
    }
    else if( outStr.contains( "END" ) )
    {
        UNLOCK();
        emit sgnDone();
    }
    else
    {
        timer->start( maxtimeout );
    }
}

//-------------------------------------

void QueryMicroMan::onTimeout()
{
    timer->stop();
    emit sgnSendResponse( TIMEOUTED_STR );
    UNLOCK();
}

//-------------------------------------

void QueryMicroMan::LOCK()
{
    mtx.lock();
    //locker = new Locker< QueryMicroMan >( this );
    locked = true;
}

//-------------------------------------

void QueryMicroMan::UNLOCK()
{
    mtx.unlock();

    /*if( locker )
    {
        delete locker;
        locker = 0;
    }*/
    locked = false;
}

//-------------------------------------








